import axios from 'axios' 
import { ElMessage } from 'element-plus'  
import pinia from '@/stores/store'
import { useUserStore } from '@/stores/user'
import router from '@/router'
 
 
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000,
    withCredentials: true
}) 
 

// 请求拦截器
service.interceptors.request.use(
  config => {    
    const store = useUserStore(pinia)
    if(store.token){
      config.headers.token = store.token
    }  
    return config // 必须返回配置
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { code, msg, data } = response.data
    //   要根据success的成功与否决定下面的操作
    if (code == 1) { 
      return data
    } else {
      // 业务错误
      ElMessage.error(msg) // 提示错误消息
      return Promise.reject(new Error(msg))
    }
  },
  error => {
      console.log("🚀 ~ error:", error)
    if(error.response.status == 401){
      const store = useUserStore(pinia)
      store.clearToken()
     setTimeout(() => {
        window.location.href = '/login'
      }, 800)
    }
    // 处理 token 超时问题 
   ElMessage.error(error.response.data.msg) // 提示错误信息
    return Promise.reject(error)
  }
)

export default service
